package study.service.attachment;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import study.domain.attachment.Attachment;
import study.domain.attachment.AttachmentType;

import com.barney.support.image.ImageManager;

/**
 * 첨부파일 이미지 서비스
 *
 * @author Barney Kim
 */
@Service
public class AttachmentImageService {

	@Resource(name = "imageManager")
	private ImageManager imageManager;

	public void resize(File original, String attachmentRootPath, Attachment attachment) {
		resize(original, attachmentRootPath, attachment, true);
	}

	public void resize(File original, String attachmentRootPath, Attachment attachment,
			boolean keepRatio) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(original);
			BufferedImage srcImg = ImageIO.read(fileInputStream);
			attachment.setImageWidth(srcImg.getWidth());
			attachment.setImageHeight(srcImg.getHeight());

			for (AttachmentType type : AttachmentType.values()) {
				if (type == AttachmentType.ORIGINAL)
					continue;

				boolean needResize = srcImg.getWidth() > type.getMaxWidth()
						|| srcImg.getHeight() > type.getMaxHeight();

				if (!needResize) {
					continue;
				}
				File dest = new File(attachmentRootPath, attachment.getFilePath(type));
				imageManager.resize(srcImg, dest, type.getMaxWidth(), type.getMaxHeight(),
						keepRatio);
			}

		} catch (IOException ioe) {
			throw new RuntimeException(ioe.getMessage(), ioe);
		} finally {
			IOUtils.closeQuietly(fileInputStream);
		}
	}
}
